package com.atyuntuku.yuntuku.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.atyuntuku.yuntuku.common.BaseResponse;
import com.atyuntuku.yuntuku.common.ResultUtils;
import com.atyuntuku.yuntuku.constant.UserConstant;
import com.atyuntuku.yuntuku.controller.request.UserAddRequest;
import com.atyuntuku.yuntuku.controller.request.UserQueryRequest;
import com.atyuntuku.yuntuku.controller.request.UserRegisterRequest;
import com.atyuntuku.yuntuku.exception.ErrorCode;
import com.atyuntuku.yuntuku.exception.ThrowUtils;
import com.atyuntuku.yuntuku.mapper.UserMapper;
import com.atyuntuku.yuntuku.pojo.User;
import com.atyuntuku.yuntuku.service.UserService;
import com.atyuntuku.yuntuku.utils.CommonUtils;
import com.atyuntuku.yuntuku.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestPart;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * ClassName: UserServiceImpl
 * Package: com.atyuntuku.yuntuku.service.impl
 * Description:
 *
 * @Author qinglong wei
 * @Create 2025/10/5 11:31
 * @Version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public BaseResponse<Boolean> userRegister(UserRegisterRequest userRegisterRequest) {
         //校验参数
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR,"参数不能为空");

        //参数合法性校验
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount,userPassword,checkPassword),ErrorCode.PARAMS_ERROR,"参数不能为空");
        ThrowUtils.throwIf(userAccount.length()<3,ErrorCode.PARAMS_ERROR,"账户名称长度不能小于3位");
        ThrowUtils.throwIf(userPassword.length()<6,ErrorCode.PARAMS_ERROR,"密码不能小于6位");
        ThrowUtils.throwIf(!userPassword.equals(checkPassword),ErrorCode.PARAMS_ERROR,"两次密码输入不一致");

        //非法字符判断
        String invalidpattern="[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern pattern = Pattern.compile(invalidpattern);
        Matcher matcher = pattern.matcher(userAccount);
        ThrowUtils.throwIf(matcher.find(),ErrorCode.PARAMS_ERROR,"账户名不能含有非法字符");

        //查询账户名是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account",userAccount);
        User one = this.getOne(queryWrapper);
        ThrowUtils.throwIf(one!=null,ErrorCode.PARAMS_ERROR,"账户名重复，请重写账户名");

        //给密码进行加密
        String encryptPassword = getEncryptPassword(userPassword);

        //插入数据库
         User user = new User();
         user.setUserAccount(userAccount);
         user.setUserPassword(encryptPassword);
         user.setUserName(userAccount);
         user.setUserAvatar("https://ts1.tc.mm.bing.net/th/id/OIP-C.JEbn_0k0K4xWRH8KHTpITQHaHa?cb=12&rs=1&pid=ImgDetMain&o=7&rm=3");
         user.setUserProfile("快来介绍一下自己吧~");
         user.setUserRole("user");
         user.setEditTime(new Date());
         user.setCreateTime(new Date());
         user.setUpdateTime(new Date());
         user.setIsDeleted(0);

        boolean save = this.save(user);
        return  ResultUtils.success(save);
    }

    @Override
    public BaseResponse<UserVO> userlogin(String userAccount, String userPassword, HttpServletRequest request) {
        //校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount,userPassword),ErrorCode.PARAMS_ERROR,"参数不能为空");
        ThrowUtils.throwIf(userAccount.length()<3,ErrorCode.PARAMS_ERROR,"账户名长度不小于3位");
        ThrowUtils.throwIf(userPassword.length()<6,ErrorCode.PARAMS_ERROR,"密码长度不能小于6位");

        //加密
        String encryptPassword = getEncryptPassword(userPassword);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account",userAccount).eq("user_password",encryptPassword);
        User user = this.getOne(queryWrapper);
        ThrowUtils.throwIf(user == null,ErrorCode.PARAMS_ERROR,"账户名或密码错误");
        System.out.println(user);
        //保存用户状态到session域
        HttpSession session = request.getSession();
        session.setAttribute(UserConstant.USER_LOGIN_STATE,user);
        session.setMaxInactiveInterval(1209600);

        return  ResultUtils.success(getUserVO(user));
    }

    @Override
    public BaseResponse<Boolean> userlogout(HttpServletRequest request) {
        User currentUser = CommonUtils.getCurrentUser(request);
        ThrowUtils.throwIf(currentUser == null,ErrorCode.NOT_LOGIN_ERROR,"登出失败,请先登录");
        System.out.println("移除登录状态！！！！！");
        //移除登录状态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return  ResultUtils.success(true);
    }

    @Override
    public List<UserVO> getUserVOList(List<User> list) {
        if(CollectionUtil.isEmpty(list))
        {
            return new ArrayList<>();
        }

        return list.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public BaseResponse<Boolean> addUser(UserAddRequest userAddRequest) {

        ThrowUtils.throwIf(userAddRequest == null,ErrorCode.PARAMS_ERROR,"参数不能为空");
        User user = new User();
        BeanUtil.copyProperties(userAddRequest,user);
        final String DEFAULT_PASSWORD = "123456";
        String encryptPassword = getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        boolean save = this.save(user);
        ThrowUtils.throwIf(!save,ErrorCode.SYSTEM_ERROR,"插入失败，请重试");
        return  ResultUtils.success(true);
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userAvatar = userQueryRequest.getUserAvatar();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        int current = userQueryRequest.getCurrent();
        int pageSize = userQueryRequest.getPageSize();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(userAccount),"user_account",userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName),"user_name",userName);
        queryWrapper.eq(StrUtil.isNotBlank(userRole),"user_name",userRole);
        queryWrapper.like(StrUtil.isNotBlank(userProfile),"user_profile",userProfile);
        queryWrapper.orderBy(StrUtil.isNotBlank(sortField),"ascend".equals(sortOrder),sortField);
        return queryWrapper;
    }

    @Override
    public JSONObject getUserListPage(UserQueryRequest queryRequest) {
        ThrowUtils.throwIf(ObjectUtil.isEmpty(queryRequest), ErrorCode.PARAMS_ERROR, "查询参数不能为空");
        QueryWrapper<User> queryWrapper = getQueryWrapper(queryRequest);
        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        IPage<User> page = userMapper.selectPage(new Page<>(current, pageSize), queryWrapper);
        System.out.println("page = " + JSONUtil.toJsonStr(page).toString());
        JSONObject res = new JSONObject();
        List<User> userList = page.getRecords();
        List<UserVO> userVOList = getUserVOList(userList);
        res.put("total",this.count());
        res.put("data", ResultUtils.success(userVOList));

        IPage<User> pages = userMapper.selectUserPages(new Page<>(current,pageSize));
        System.out.println("pages = " + JSONUtil.toJsonStr(pages).toString());
        return  res;
    }

    @Override
    public UserVO getUserVo(User user) {
        if (user == null)
        {
            return null;
        }
        UserVO newUsr = new UserVO();
        BeanUtil.copyProperties(user,newUsr);
        return newUsr;
    }


    @Override
    public BaseResponse<UserVO> getUserById(Long id) {
        ThrowUtils.throwIf(ObjectUtil.isEmpty(id),ErrorCode.PARAMS_ERROR,"id不能为空");
        User user = this.getById(id);
        ThrowUtils.throwIf(user==null,ErrorCode.PARAMS_ERROR,"查询用户不存在");
        return  ResultUtils.success(getUserVO(user));
    }

    public String getEncryptPassword(String password)
    {
        String salt = "dcjiwehnefijnri";
        return  DigestUtils.md5DigestAsHex((salt+password).getBytes());
    }


    public UserVO getUserVO(User user)
    {
        UserVO newuser = new UserVO();
        BeanUtil.copyProperties(user,newuser);
        return newuser;
    }
}
